﻿using DiLe.Mes.Application.Common;
using DiLe.Mes.Cloud.Controllers.SystemManage.Organization.Parameters;
using DiLe.Mes.Model.Common.Organization.Entity;

namespace DiLe.Mes.Cloud.Controllers.SystemManage.Organization {
    /// <summary>
    /// 角色
    /// </summary>
    [ApiExplorerSettings(GroupName = ApiCloudGroupConst.Organization)]
    public class RoleController : ApiBaseController {
        /// <summary>
        /// 
        /// </summary>
        private readonly OrganizationClient _organizationClient;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="organization"></param>
        public RoleController(OrganizationClient organization) {
            _organizationClient = organization;
        }

        /// <summary>
        /// 获取角色信息列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetRoleList(QueryParameter parameter) {
            var whereExpression = Expressionable.Create<RoleEntity>();
            if (!parameter.Keyword.IsNullOrEmpty()) {
                whereExpression.And(p => p.Name.Contains(parameter.Keyword));
            }
            if (parameter.Pagination == null) {
                var res = await _organizationClient.GetRoleListAsync(whereExpression.ToExpression());
                await FillRoleExjosn(res);
                return Success(res);
            } else {
                var res = await _organizationClient.GetRolePageListAsync(whereExpression.ToExpression(), parameter.Pagination);
                await FillRoleExjosn(res.Record);
                return Success(res);
            }
        }
        /// <summary>
        /// 获取角色信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetRoleInfo(long id) {
            var res = await _organizationClient.GetRoleInfoAsync(id);
            await FillRoleExjosn(new List<RoleEntity> { res });
            return Success(res);
        }
        /// <summary>
        /// 保存角色信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> SaveRole(RoleParameter roleParameter) {
            var rolId = await _organizationClient.SaveRoleAsync(roleParameter.Model!);
            if (roleParameter.Relations.Count > 0) {
                await _organizationClient.SaveUserRoleAsync(rolId, roleParameter.Relations);
            }
            return Success();
        }
        /// <summary>
        /// 删除角色信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> DeleteRole(List<long> ids) {
            var res = await _organizationClient.DeleteRoleAsync(ids);
            return res ? Success() : Fail();
        }
        /// <summary>
        /// 更新角色状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> UpdateRoleStatus(CommomParameter parameter) {
            var res = await _organizationClient.UpdateRoleStatusAsync(parameter.Ids, parameter.Status);
            return Success(res);
        }
        #region 其他方法
        /// <summary>
        /// 
        /// </summary>
        /// <param name="roles"></param>
        private async Task FillRoleExjosn(List<RoleEntity> roles) {
            if (!roles.Any()) {
                return;
            }
            var ids = roles.ConvertAll(p => p.Id);
            var userReleList = await _organizationClient.GetUserRoleListAsync(ids);
            var userIds = userReleList.Select(p => p.UserId).Distinct().ToList();
            var userList = await _organizationClient.GetUserListByIdAsync(userIds);

            foreach (var item in roles) {
                var tempIds = userReleList?.Where(p => p.RoleId == item.Id).Select(p => p.UserId).Distinct().ToList();
                if (tempIds == null || !tempIds.Any()) {
                    continue;
                }
                var temps = userList?.Where(p => tempIds!.Contains(p.Id)).ToList();
                item.ExtJson.Add("UserIds", string.Join(",", temps?.ConvertAll(p => p.Id)!));
                item.ExtJson.Add("UserNames", string.Join(",", temps?.ConvertAll(p => p.Name)!));
            }
        }
        #endregion
    }
}
